package cn.wolfcode.luowowo.service.impl;

import cn.wolfcode.luowowo.domain.StrategyCatalog;
import cn.wolfcode.luowowo.exception.LogicException;
import cn.wolfcode.luowowo.query.StrategyCatalogQuery;
import cn.wolfcode.luowowo.repository.StrategyCatalogRepository;
import cn.wolfcode.luowowo.service.IDestinationService;
import cn.wolfcode.luowowo.service.IStrategyCatalogService;
import cn.wolfcode.luowowo.util.DBHelper;
import cn.wolfcode.luowowo.util.MyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;

//攻略分类业务实现类
@Service
public class StrategyCatalogServiceImpl implements IStrategyCatalogService {
    //注入攻略分类数据接口
    @Autowired
    private StrategyCatalogRepository strategyCatalogRepository;

    @Autowired
    private MongoTemplate mongoTemplate;
    //注入目的地服务
    @Autowired
    private IDestinationService destinationService;


    //根据攻略分类id查询攻略分类信息
    @Override
    public StrategyCatalog get(String id) {
        return strategyCatalogRepository.findById(id).orElse(null);
    }

    @Override
    public void save(StrategyCatalog strategyCatalog) {
        //防止调用者传了id覆盖了数据
        strategyCatalog.setId(null);
        MyUtils.hasLength(strategyCatalog.getName() , "名称不能为空");
        MyUtils.hasLength(strategyCatalog.getDestId() , "目的地不能为空");
        MyUtils.isSequence(strategyCatalog.getSequence());
        //查询目的地的名字存入分类
        strategyCatalog.setDestName(destinationService.get(strategyCatalog.getDestId()).getName());
        strategyCatalogRepository.save(strategyCatalog);
    }

    @Override
    public void update(StrategyCatalog strategyCatalog) {
        MyUtils.hasLength(strategyCatalog.getId() , "编辑的id不能为空");
        MyUtils.hasLength(strategyCatalog.getName() , "名称不能为空");
        MyUtils.hasLength(strategyCatalog.getDestId() , "目的地不能为空");
        MyUtils.isSequence(strategyCatalog.getSequence());
        //查询目的地的名字存入分类
        strategyCatalog.setDestName(destinationService.get(strategyCatalog.getDestId()).getName());
        strategyCatalogRepository.save(strategyCatalog);
    }

    @Override
    public void delete(String id) {
        strategyCatalogRepository.deleteById(id);
    }

    //分页查询
    @Override
    public Page<StrategyCatalog> list(StrategyCatalogQuery qo) {
        //创建条件对象
        Query query = new Query();
        //调用数据库工具类查询
        return DBHelper.PagingQuery(mongoTemplate, query, StrategyCatalog.class,qo.getPageable());
    }

    @Override
    public List<StrategyCatalog> findByDestId(String destId) {
        return strategyCatalogRepository.findByDestId(destId);
    }
}
